package com.dodock.banglapapers.server.helper;

import java.io.IOException;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class DDNNewsDetailIttefaq {

	public String Generate(String newsid) throws IOException {
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();
		try {
			Entity detailsEntity = datastore.get(KeyFactory.createKey(
					"NewsDetails", "ittefaq__" + newsid));
			Text text = (Text) detailsEntity.getProperty("data");
			String data = Settings.replaceExtras(text.getValue());
			return data;
		} catch (EntityNotFoundException e) {
			String url = Settings.WWW_ITTEFAQ_COM + newsid;
			Connection.Response response = Jsoup
					.connect(url)
					.userAgent(
							"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
					.timeout(10000).execute();

			Document doc = response.parse();
			JsonObject news = new JsonObject();
			news.addProperty("id", newsid);
			news.addProperty("sharelink", url);

			Element newsDetailElement = doc.select("div[class=detailsNewsDtl]")
					.first();
			if (newsDetailElement != null) {
				JsonArray imageArray = new JsonArray();
				Elements imageElements = newsDetailElement.select("img");
				String image;
				boolean hasImage = false;
				for (Element imageElement : imageElements) {
					image = imageElement.attr("src").trim();
					JsonObject obj = new JsonObject();
					obj.addProperty("url", Settings.WWW_ITTEFAQ_COM + image);
					hasImage = true;
					imageArray.add(obj);
				}

				if ((hasImage))
					news.add("gallery", imageArray);

				news.addProperty("details", newsDetailElement.text()
						.replaceAll("\u00a0", "<br/>"));

				String data = news.toString();
				data = Settings.replaceExtras(data);
				Text text = new Text(data);
				Entity detailsEntity = new Entity("NewsDetails", "ittefaq__"
						+ newsid);
				detailsEntity.setProperty("data", text);
				datastore.put(detailsEntity);
				return data;
			} else {
				return "{}";
			}
		}
	}

	/*private String replaceExtras(String string) {
		string = string.replaceAll("&quot;", "\"");
		string = string.replaceAll("&apos;", "'");
		string = string.replaceAll("&amp;", "&");
		string = string.replaceAll("&lt;", "<");
		string = string.replaceAll("&gt;", ">");
		// string = string.replaceAll("\u00a0", "\n");
		return string;
	}*/

}
